//
//  QKEasyClipsAlbumController.m
//  EasyIOS
//
//  Created by ChiCo on 2017/5/3.
//  Copyright © 2017年 EasyIOS. All rights reserved.
//

#import "QKEasyClipsAlbumController.h"
#import <Photos/Photos.h>
#import "QKEasyClipsAlbumCell.h"
#import "QKEasyAlbumTopBar.h"
#import "QKClipsDetailController.h"

@interface QKEasyClipsAlbumController () <UICollectionViewDelegate,UICollectionViewDataSource,PHPhotoLibraryChangeObserver>



/**
 * asset: 裁剪后的照片 如果没有选择，照片为nil
 */
@property (nonatomic,copy)void (^finish)(UIImage *image);


/**
 * 可供展示的照片
 */
@property (nonatomic,strong)PHFetchResult *fetchResult;


@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,assign)CGFloat radio;

@end

@implementation QKEasyClipsAlbumController


/**
 * 从相册裁剪一张照片
 * controller 当前控制器
 * radio 裁剪图片的宽高比例
 * image 裁剪过后的图片 没有选择照片则为nil
 */
+ (QKEasyClipsAlbumController *)clipsPhotoWithController:(UIViewController *)controller
                                                   radio:(CGFloat)radio
                                                  finish:(void (^)(UIImage *image))finish
{
    QKEasyClipsAlbumController *album = [[QKEasyClipsAlbumController alloc] init];
    album.radio = radio;
    album.finish = finish;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:album];
    nav.navigationBarHidden = YES;
    [controller presentViewController:nav
                             animated:YES
                           completion:NULL];
    return album;
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setUpSubViews];
    [self loadData];
    
    [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
    
}

- (void)photoLibraryDidChange:(PHChange *)changeInstance
{
    //改变数据了,重新加载一下
    [self loadData];
    
}
- (void)loadData
{
    //没有权限要申请权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
        NSDictionary *mainInfoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [mainInfoDictionary objectForKey:@"CFBundleDisplayName"];
        NSString *alerString = [NSString stringWithFormat:@"允许%@访问你的手机相册", appName];
        UIAlertController *aletController = [UIAlertController alertControllerWithTitle:@"使用相册" message:alerString preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [aletController addAction:cancelAction];
        [aletController addAction:setAction];
        [self presentViewController:aletController animated:YES completion:NULL];
    }
    
    @weakify(self);
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus authorizationStatus) {
        @strongify(self);
        if (authorizationStatus == PHAuthorizationStatusAuthorized) {
            
            PHFetchOptions *options = [[PHFetchOptions alloc] init];
            options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
            PHFetchResult *request = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:options];
            self.fetchResult = request;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
                NSUInteger count = [self.fetchResult count];
                if (count > 0) {
                    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:(NSInteger)count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
                } else {
                    //                        LTHUD(@"还没有照片，快去拍几张吧");
                }
                
            });
        }
    }];
    
}

- (void)setUpSubViews
{
    [self setupCollectionView];
    CGFloat topHeight = 44;
    if (KScreenHeight >= 812) topHeight = 78;
    QKEasyAlbumTopBar *topBar = [[QKEasyAlbumTopBar alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, topHeight)];
    [topBar.backButton addTarget:self
                          action:@selector(cacelAction)
                forControlEvents:UIControlEventTouchUpInside];
    [topBar.cancelButton addTarget:self
                            action:@selector(cacelAction)
                  forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBar];
    
    
}

- (void)cacelAction
{
    if (self.finish) {
        self.finish(nil);
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)setupCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 2.5;
    layout.minimumInteritemSpacing = 2.5;
    CGFloat width = (KScreenWidth-12.5)/4;
    layout.itemSize = CGSizeMake(width, width);
    self.title = @"全部照片";
    CGFloat topHeight = 44;
    if (KScreenHeight >= 812) topHeight = 78;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(2.5, topHeight, KScreenWidth-5, KScreenHeight-topHeight) collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    [self.collectionView setDelegate:self];
    [self.collectionView setDataSource:self];
    [self.collectionView registerClass:[QKEasyClipsAlbumCell class] forCellWithReuseIdentifier:@"EasyClipsAlbumCell"];
    [self.collectionView setBackgroundColor:[UIColor blackColor]];
    [self.view setBackgroundColor:[UIColor blackColor]];
    
    //滚动视图不需要全屏切换
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    // Fallback on earlier versions
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return (NSInteger)[self.fetchResult count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    QKEasyClipsAlbumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EasyClipsAlbumCell" forIndexPath:indexPath];
    cell.asset = [self.fetchResult objectAtIndex:(NSUInteger)indexPath.row];
    
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    QKEasyClipsAlbumCell *cell = (QKEasyClipsAlbumCell *)[collectionView cellForItemAtIndexPath:indexPath];
    QKClipsDetailController *controller = [[QKClipsDetailController alloc] initWithAsset:cell.asset radio:self.radio finish:^(UIImage *image) {
        if (self.finish) {
            self.finish(image);
        }
        [self dismissViewControllerAnimated:YES completion:NULL];
    }];
    [self.navigationController pushViewController:controller animated:YES];
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)dealloc
{
    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}

@end
